import { animate, state, style, transition, trigger } from '@angular/animations';
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { List, Map } from 'immutable';
import 'rxjs/add/operator/combineLatest';
import { addTodo, completeTodo, deleteTodo, filterTodo } from './actions';
import { Todo } from './model/todo';

const FILTERS = Map({
  All: () => true,
  Complete: (todo) => todo.completed,
  Pending: (todo) => !todo.completed
})

@Component({
  selector: 'cs-todolist',
  templateUrl: './todolist.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  animations: [
    trigger('shrinkOut', [
      state('in', style({})),
      transition('* => void', [
        style({ height: '*', opacity: 1 }),
        animate(1000, style({ height: 0, opacity: 0 }))
      ]),
      transition('void => *', [
        style({ height: 0, opacity: 0 }),
        animate(1000, style({ height: '*', opacity: 1 }))
      ])
    ])
  ]
})
export class TodolistComponent implements OnInit {
  private filterActions = [ 'All', 'Complete', 'Pending' ]
  private todos$
  private filterName

  constructor(private store$: Store<any>) {
    this.todos$ = store$.select('todos').combineLatest(
      store$.select('filterTodo'),
      (todos_: List<Todo>, filter_: string) => {
        this.filterName = filter_
        return todos_.filter(FILTERS.get(filter_, FILTERS.get('All')))
      }
    )
  }

  ngOnInit() {
  }

  onCreate(todo: Todo) {
    this.store$.dispatch(addTodo(todo))
  }

  onComplete(todo: Todo) {
    this.store$.dispatch(completeTodo(todo))
  }

  onDelete(todo: Todo) {
    this.store$.dispatch(deleteTodo(todo))
  }

  toggleFilter(event) {
    this.store$.dispatch(filterTodo(event.value))
  }

  trackByTodo(index: number, todo: Todo) {
    return todo.id
  }
}
